package com.zb.frame.base.utils.encrypt;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * MD5 加密工具类
 * @author bangzz
 */
public class MD5Util {

    private static Integer baseHashIterations = 2;
    private static String baseSalt = "salt";
    private static String baseCharset = "UTF-8";

    public static String encrypt(String str) {
        return encrypt(str, baseSalt, baseHashIterations, baseCharset);
    }

    public static String encrypt(String str, String salt) {
        return encrypt(str, salt, baseHashIterations,  baseCharset);
    }

    public static String encrypt(String str, String salt, Integer hashIterations) {
        return encrypt(str, salt, hashIterations,  baseCharset);
    }

    /**
     * MD5加密字符串（32位）
     * @param str 需要进行MD5加密的字符串
     * @param salt 加密盐
     * @param hashIterations 加密次数
     * @param charset 字符编码
     * @return
     */
    public static String encrypt(String str, String salt, Integer hashIterations, String charset) {
        String ret = str;
        for (int i = 0; i < hashIterations; i++) {
            byte[] hash = null;
            //创建一个MD5算法对象，并获得MD5字节数组,16*8=128位
            try {
                hash = MessageDigest.getInstance("MD5").digest((ret + salt).getBytes(charset));
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            ret = bytesToHex(hash);
        }
        return ret;
    }

    /**
     * 二进制换为十六进制字符串
     * @param hash
     * @return
     */
    public static String bytesToHex(byte[] hash) {
        StringBuilder hex = new StringBuilder(hash.length * 2);
        for (byte b : hash) {
            if ((b & 0xFF) < 0x10) hex.append("0");
            hex.append(Integer.toHexString(b & 0xFF));
        }
        return hex.toString();
    }

    public static void main(String[] args) {
        String str = encrypt("111111");
        System.out.println(str);//32位
        String str2 = encrypt("111111","",1);
        System.out.println(str2);//32位
    }
}
